import { HttpRequestHeader } from './HttpHeader'
import { HttpMethod } from './HttpMethod'
import { HttpRequestBuild } from './HttpRequestBuild'
import { HttpVersion } from './HttpVersion'

export type HttpQuery = Map<string, string | Array<string>> | Record<string, string | Array<string>>

/**
 * HttpRequest
 * @author 冰凝
 * @date 2022-07-01 下午 05:15
 **/
export class HttpRequest<T = string> {

    // HTTP 协议参数
    /**
     * 协议版本
     */
    public version: HttpVersion
    /**
     * 请求方法
     */
    public method: HttpMethod
    /**
     * 请求路径
     */
    public path: string
    /**
     * 查询参数 (?之后)
     */
    public query: HttpQuery
    /**
     * URL 锚点参数 (#之后)
     */
    public anchor: string
    /**
     * 请求 Header
     */
    public header: HttpRequestHeader
    /**
     * 请求体
     */
    public body: T

    // 请求控制参数
    /**
     * 请求超时, 单位: 毫秒
     */
    public timeout: number
    /**
     * 读取超时, 单位: 毫秒
     */
    public readTimeout: number

    // 成员方法

    /**
     * 构建器
     */
    public static build<T = string>(version: HttpVersion = HttpVersion.HTTP_1_1): HttpRequestBuild<T> {
        return new HttpRequestBuild<T>(version)
    }

    /**
     * 转报文消息
     */
    public toProtocolMessage(): string {
        return `
        ${ this.method } ${ this.formatUrl() }
        
        ${ this.header }
        
        ${ this.body }
        `
    }

    private formatUrl(): string {
        const {path, query, anchor} = this
        if (!query && !anchor) {
            return path || ''
        }

        let url = path

        if (query) {
            // TODO:...
            url += query
        }
        if (anchor) {
            // TODO:...
            url += anchor
        }

        return url
    }

}
